const HISTORY_KEY = 'nl2sql_history'
const MAX_HISTORY_LENGTH = 20

export const getQueryHistory = () => {
  try {
    const history = localStorage.getItem(HISTORY_KEY)
    return history ? JSON.parse(history) : []
  } catch {
    return []
  }
}

export const addQueryHistory = (query, resultCount) => {
  try {
    const history = getQueryHistory()
    const newEntry = {
      query,
      resultCount,
      timestamp: new Date().toLocaleString()
    }
    
    // 移除重复的查询
    const uniqueHistory = history.filter(item => item.query !== query)
    
    // 添加新查询到开头
    uniqueHistory.unshift(newEntry)
    
    // 限制历史记录数量
    if (uniqueHistory.length > MAX_HISTORY_LENGTH) {
      uniqueHistory.pop()
    }
    
    localStorage.setItem(HISTORY_KEY, JSON.stringify(uniqueHistory))
    return uniqueHistory
  } catch {
    return []
  }
}

export const clearQueryHistory = () => {
  try {
    localStorage.removeItem(HISTORY_KEY)
    return true
  } catch {
    return false
  }
} 